<template>
  <div class="zod-builder">
    <el-container>
      <el-aside width="300px">
        <el-card class="rule-types">
          <template #header>
            <div class="card-header">
              <span>验证规则类型</span>
            </div>
          </template>
          <el-menu>
            <el-menu-item 
              v-for="type in ruleTypes" 
              :key="type.value"
              @click="addRule(type.value)"
            >
              <el-icon><component :is="type.icon" /></el-icon>
              <span>{{ type.label }}</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-aside>
      
      <el-main>
        <el-card class="rule-config-card">
          <template #header>
            <div class="card-header">
              <span>规则配置</span>
              <el-button type="primary" @click="generateSchema">生成规则</el-button>
            </div>
          </template>

          <!-- 对象规则配置 -->
          <el-scrollbar>
            <div class="rule-config">
              <el-tree
                :data="ruleTree"
                node-key="id"
                default-expand-all
              >
                <template #default="{ node, data }">
                  <div class="rule-node">
                    <span class="node-label">{{ data.name }}</span>
                    
                    <!-- 规则配置表单 -->
                    <el-form 
                      v-if="data.type" 
                      :model="data"
                      label-width="100px"
                      class="rule-form"
                    >
                      <div class="form-content">
                        <!-- 通用配置 -->
                        <div class="form-section">
                          <el-form-item label="字段名">
                            <el-input v-model="data.name" placeholder="输入字段名" />
                          </el-form-item>
                          
                          <el-form-item label="是否必填">
                            <el-switch v-model="data.required" />
                          </el-form-item>
                        </div>

                        <!-- 字符串类型特有配置 -->
                        <div v-if="data.type === 'string'" class="form-section">
                          <el-form-item label="最小长度">
                            <el-input-number v-model="data.min" :min="0" />
                          </el-form-item>
                          
                          <el-form-item label="最大长度">
                            <el-input-number v-model="data.max" :min="0" />
                          </el-form-item>
                          
                          <el-form-item label="验证类型">
                            <el-select v-model="data.validationType">
                              <el-option label="无" value="" />
                              <el-option label="邮箱" value="email" />
                              <el-option label="URL" value="url" />
                            </el-select>
                          </el-form-item>
                        </div>

                        <!-- 数字类型特有配置 -->
                        <template v-if="data.type === 'number'">
                          <el-form-item label="最小值">
                            <el-input-number v-model="data.min" />
                          </el-form-item>
                          
                          <el-form-item label="最大值">
                            <el-input-number v-model="data.max" />
                          </el-form-item>
                          
                          <el-form-item label="整数">
                            <el-switch v-model="data.int" />
                          </el-form-item>
                        </template>

                        <!-- 数组类型特有配置 -->
                        <template v-if="data.type === 'array'">
                          <el-form-item label="最小长度">
                            <el-input-number v-model="data.min" :min="0" />
                          </el-form-item>
                          
                          <el-form-item label="最大长度">
                            <el-input-number v-model="data.max" :min="0" />
                          </el-form-item>
                          
                          <el-button @click="addArrayItem(data)">添加数组项</el-button>
                        </template>

                        <div class="form-actions">
                          <el-button 
                            v-if="data.type === 'object'"
                            @click="addObjectField(data)"
                          >
                            添加字段
                          </el-button>

                          <el-button 
                            v-if="data.type === 'array'"
                            @click="addArrayItem(data)"
                          >
                            添加数组项
                          </el-button>

                          <el-button 
                            type="danger" 
                            @click="removeRule(node, data)"
                          >
                            删除
                          </el-button>
                        </div>
                      </div>
                    </el-form>
                  </div>
                </template>
              </el-tree>
            </div>
          </el-scrollbar>
        </el-card>
      </el-main>

      <el-drawer
        v-model="showCode"
        title="生成的验证规则"
        direction="rtl"
        size="50%"
      >
        <pre><code>{{ generatedCode }}</code></pre>
        <el-button @click="copyCode">复制代码</el-button>
      </el-drawer>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Edit, List, Setting } from '@element-plus/icons-vue'
import { nanoid } from 'nanoid'

// 规则类型定义
const ruleTypes = [
  { label: '字符串', value: 'string', icon: Document },
  { label: '数字', value: 'number', icon: Edit },
  { label: '数组', value: 'array', icon: List },
  { label: '对象', value: 'object', icon: Setting }
]

// 规则树
const ruleTree = ref([{
  id: nanoid(),
  name: 'root',
  type: 'object',
  children: []
}])

// 生成的代码
const generatedCode = ref('')
const showCode = ref(false)

// 添加新规则
function addRule(type: string) {
  const newRule = {
    id: nanoid(),
    name: `new${type}`,
    type,
    required: true,
    children: type === 'object' ? [] : undefined
  }
  
  ruleTree.value[0].children.push(newRule)
}

// 删除规则
function removeRule(node: any, data: any) {
  const parent = node.parent
  const children = parent.data.children
  const index = children.findIndex((d: any) => d.id === data.id)
  children.splice(index, 1)
}

// 添加对象字段
function addObjectField(data: any) {
  if (!data.children) {
    data.children = []
  }
  
  data.children.push({
    id: nanoid(),
    name: 'newField',
    type: 'string',
    required: true
  })
}

// 添加数组项
function addArrayItem(data: any) {
  if (!data.items) {
    data.items = {
      id: nanoid(),
      type: 'string',
      required: true
    }
  }
}

// 生成验证规则代码
function generateSchema() {
  const schema = convertToZodSchema(ruleTree.value[0])
  generatedCode.value = `import { createZodSchema } from '@/utils/create-zod-schema'\n\n` +
    `const schema = createZodSchema(${JSON.stringify(schema, null, 2)})`
  showCode.value = true
}

// 转换为 Zod Schema 格式
function convertToZodSchema(node: any) {
  const schema: any = {
    type: node.type
  }

  if (node.required !== undefined) {
    schema.required = node.required
  }

  if (node.type === 'string' || node.type === 'number') {
    if (node.min !== undefined) schema.min = node.min
    if (node.max !== undefined) schema.max = node.max
    if (node.type === 'string' && node.validationType) {
      schema[node.validationType] = true
    }
    if (node.type === 'number' && node.int) {
      schema.int = true
    }
  }

  if (node.type === 'array' && node.items) {
    schema.items = convertToZodSchema(node.items)
  }

  if (node.type === 'object' && node.children) {
    schema.shape = {}
    node.children.forEach((child: any) => {
      schema.shape[child.name] = convertToZodSchema(child)
    })
  }

  return schema
}

// 复制生成的代码
function copyCode() {
  navigator.clipboard.writeText(generatedCode.value)
  ElMessage.success('代码已复制到剪贴板')
}
</script>

<style scoped>
.zod-builder {
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.el-container {
  height: 100%;
}

.el-main {
  padding: 0 0 0 20px;
  height: 100%;
}

.rule-config-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.rule-config-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

.rule-config-card :deep(.el-scrollbar) {
  height: 100%;
}

.rule-config {
  padding: 20px;
  min-height: calc(100vh - 160px);
}

.rule-types {
  margin-right: 0;  /* 移除右边距，因为 el-main 已经有左边距 */
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rule-node {
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
  width: 100%;
  min-height: 40px;
}

.node-label {
  min-width: 120px;
  padding: 6px 0;
}

.rule-form {
  flex: 1;
  margin-left: 20px;
}

.form-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-section {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 8px 0;
}

.form-section .el-form-item {
  margin-bottom: 0;
  min-width: 250px;  /* 增加最小宽度 */
  flex: 1;
}

.form-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

pre {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

:deep(.el-tree-node__children) {
  padding-left: 24px;
}

/* 美化滚动条 */
:deep(.el-scrollbar__bar.is-horizontal) {
  display: none;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}
</style>
